package util;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Silvanei S
 */
public class CPFField extends PlainDocument{
    
    public static final int NUMERO_DIGITOS_MAXIMO = 14; 
    //043.206.769-80

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { 

        String texto = getText(0, getLength());
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (!Character.isDigit(c) && c != '.' && c != '-') {
                return;
            }
            
            if(c == '.' && (i != 3 && i != 7)){
                return;
            }
            if(c == '-' && i != 11){
                return;
            }
        }

        if (texto.length() < CPFField.NUMERO_DIGITOS_MAXIMO) {
            super.remove(0, getLength()); 
            StringBuilder s = new StringBuilder(texto + str);
            
            if (s.length() == 3 || s.length() == 4) {
                s.insert(3, ".");
            } else if (s.length() == 7 || s.length() == 8) {
                s.insert(7, ".");
            }else if(s.length() == 11 || s.length() == 12){
                s.insert(11, "-");
            }

            super.insertString(0, s.toString(), a);
        }
    }
} 
